use sea_orm::{DbErr, Set};

use crate::api::account_info_request::get_account_info_list;
use crate::entity::convert;
use crate::utils::app::{get_date_time, merge_json_str, to_json_str};
use crate::utils::db_util;

pub async fn clean_data() -> Result<(), DbErr> {
    db_util::get_global_db_util().execute_without_params("delete from account_info").await?;
    log::error!("clean_data");
    Ok(())
}
pub async fn syn_zh(delete_flag: i32) -> Result<(), DbErr> {
    let acc_list = get_account_info_list().await;
    if acc_list.is_none() || acc_list.as_ref().unwrap().is_empty() {
        log::error!("没有账号,flag={}", delete_flag);
        if delete_flag == 1 {
            clean_data().await?;
        }
        return Ok(());
    }

    let sql = "SELECT id,zh,zh_cfg FROM account_info order by usort desc,id asc";
    let params = Vec::new();

// 修改：获取 id、zh 和 zh_cfg 的映射
    let id_zh_map: Vec<(i64, String, String)> = db_util::get_global_db_util().raw_query(sql, params).await
        .map(|rows| rows.into_iter()
            .filter_map(|row| {
                let id = row["id"].as_i64()?;
                let zh = row["zh"].as_str()?.to_string();
                let zh_cfg = row["zh_cfg"].as_str()?.to_string(); // 新增字段处理
                Some((id, zh, zh_cfg))
            })
            .collect())?;

    // 如果delete_flag为1，则删除acc_list中没有的账号
    if delete_flag == 1 {
        // 收集需要删除的账号（在数据库中但不在新的账号列表中）
        let new_zh_list: Vec<&String> = acc_list.as_ref().unwrap().iter()
            .filter_map(|acc| acc.zh.as_ref())
            .collect();
            
        let ids_to_delete: Vec<i64> = id_zh_map.iter()
            .filter(|(_, zh, _)| !new_zh_list.contains(&zh))
            .map(|(id, _, _)| *id)
            .collect();
        
        // 删除不存在于新列表中的账号
        if !ids_to_delete.is_empty() {
            let ids_str: Vec<String> = ids_to_delete.iter().map(|id| id.to_string()).collect();
            let ids_list = ids_str.join(",");
            let delete_sql = format!("DELETE FROM account_info WHERE id IN ({})", ids_list);
            db_util::get_global_db_util().execute_without_params(&delete_sql).await?;
            log::info!("删除了 {} 个不在新列表中的账号，ID列表: {}", ids_to_delete.len(), ids_list);
        }
    }

// 从映射中提取 zh 列表用于快速查找
    let zh_list: Vec<String> = id_zh_map.iter().map(|(_, zh, _)| zh.clone()).collect();
    log::info!("zh_list:{:?}", zh_list);

    for acc in acc_list.as_ref().unwrap().iter() {
        if let Some(zh) = &acc.zh {
            let mut dto = convert::convert_account_active_model(acc);
            let acc_zh_cfg = match &acc.zh_cfg {
                Some(json_value) => to_json_str(json_value)
                    .ok_or_else(|| DbErr::Custom("Failed to convert JSON to string".to_string()))?,
                None => "{}".to_string(), // 如果 zh_cfg 是 None，使用空 JSON 对象
            };

            if !zh_list.contains(zh) {
                // 新增记录
                dto.hjstatus_time = Set(Some(get_date_time()));
                db_util::get_global_db_util().insert(dto).await?;
            } else {
                // 修改：查找对应的 id
                if let Some((id, _, zh_cfg_db)) = id_zh_map.iter().find(|(_, z, _)| z == zh) {
                    // 设置要更新的字段
                    dto.id = Set(*id); // 设置主键
                    dto.hjstatus_time = Set(Some(get_date_time()));

                    if let Some(merged_cfg) = merge_json_str(zh_cfg_db,&acc_zh_cfg) {
                        dto.zh_cfg = Set(Some(merged_cfg));
                    }
                    // 修改：执行更新操作并处理结果
                    db_util::get_global_db_util().update(dto).await?;
                }
            }
        }
    }

    Ok(())
}

/// 更新同步时间并执行同步操作
pub async fn syn_zh_with_time_update(delete_flag: i32) -> Result<(), DbErr> {
    use crate::config::const_store::global_store;
    use crate::utils::app::get_time;
    
    let now = get_time();
    global_store().write().syn_zhcfg.syn_zh_time = now;
    syn_zh(delete_flag).await
}
